package com.ws.boot.demo.validate.validation.validator;

import com.google.common.collect.Lists;
import com.ws.boot.demo.validate.validation.annotation.Unique;
import com.ws.boot.validate.context.ConstraintValidatorContext;
import com.ws.boot.validate.context.ValidatedBeanMetaData;
import com.ws.boot.validate.core.validator.ConstraintValidator;
import lombok.extern.slf4j.Slf4j;

import java.util.List;

/**
 * 唯一校验器 .
 *
 * @className: UniqueValidator
 * @author: ws
 * @date: 2020/4/8 14:07
 * @version: 1.0.0
 */
@Slf4j
public class UniqueValidator implements ConstraintValidator<Unique, Object> {

    /**
     * 唯一集合
     */
    private static final List<String> UNIQUE_LIST =
            Lists.newArrayList("abcde12345", "13100001111");


    /**
     * 支持的校验注解类型 .
     *
     * @return java.lang.Class<A>
     * @author ws
     * @date 2020/4/12 0:05
     **/
    @Override
    public Class<Unique> supportAnnotationType() {
        return Unique.class;
    }

    /**
     * 支持的校验对象类型 .
     *
     * @return java.lang.Class<T>
     * @author ws
     * @date 2020/4/12 0:06
     **/
    @Override
    public Class<Object> supportValidType() {
        return Object.class;
    }

    /**
     * 执行校验 .
     *
     * @param constraint
     * @param value
     * @param context
     * @return boolean
     * @author ws
     * @date 2020/3/29 23:56
     **/
    @Override
    public boolean executeValid(Unique constraint, Object value, ConstraintValidatorContext context) {
        log.info("进入了 unique 校验器");
        List<ValidatedBeanMetaData> list = context.getValidatedBeanPath();
        // 校验值，这里写死
        ValidatedBeanMetaData detail = list.get(list.size() - 1);

        if (!UNIQUE_LIST.contains(detail.getCurrentValue())) {
            return false;
        }
        return true;
    }
}
